package cn.wit.summit.chwan.ui.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.drawable.Animatable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.listener.OnPageChangeListener;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.controller.BaseControllerListener;
import com.facebook.drawee.controller.ControllerListener;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.image.ImageInfo;
import com.flyco.tablayout.SlidingTabLayout;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.wit.summit.chwan.R;
import cn.wit.summit.chwan.adapters.FragmentPagerAdapter;
import cn.wit.summit.chwan.adapters.GameLibraryTopAdapter;
import cn.wit.summit.chwan.interfaces.ScrollHeightListener;
import cn.wit.summit.chwan.models.db.NetResultCacheTable;
import cn.wit.summit.chwan.models.dbmanager.NetResultCacheManager;
import cn.wit.summit.chwan.models.dto.DiscoveryType;
import cn.wit.summit.chwan.models.dto.JumpBaseBean;
import cn.wit.summit.chwan.models.dto.PersonHomeDataUrl;
import cn.wit.summit.chwan.models.event.DownloadEvent;
import cn.wit.summit.chwan.models.event.EnergyEvent;
import cn.wit.summit.chwan.models.response.GameLibraryV3Response;
import cn.wit.summit.chwan.models.response.ResponseBase;
import cn.wit.summit.chwan.net.NetCallBack;
import cn.wit.summit.chwan.net.RpcConstant;
import cn.wit.summit.chwan.retrofit.ApiUtil;
import cn.wit.summit.chwan.retrofit.MyCallback;
import cn.wit.summit.chwan.retrofit.RetrofitManager;
import cn.wit.summit.chwan.ui.activity.SearchActivity;
import cn.wit.summit.chwan.ui.base.BaseFragment;
import cn.wit.summit.chwan.ui.base.MyApplication;
import cn.wit.summit.chwan.utils.AccountBean;
import cn.wit.summit.chwan.utils.AccountUtil;
import cn.wit.summit.chwan.utils.IntentUtil;
import cn.wit.summit.chwan.utils.NetWorkUtils;
import cn.wit.summit.chwan.utils.PreferenceUtil;
import cn.wit.summit.chwan.utils.StringUtils;
import cn.wit.summit.chwan.utils.ToastUtils;
import cn.wit.summit.chwan.utils.UtilsMy;
import cn.wit.summit.chwan.widgets.MyGridView;
import cn.wit.summit.chwan.widgets.MyViewPager;
import cn.wit.summit.chwan.widgets.RecommendTopDownloadV2View;
import cn.wit.summit.chwan.widgets.RecommendTopWalletV2View;
import io.supercharge.shimmerlayout.ShimmerLayout;
import retrofit2.Retrofit;

/**
 * Created by Alan on 2018/9/6.
 */

public class GameLibraryFragment extends BaseFragment implements ScrollHeightListener {

    @Bind(R.id.recommendTopWallet)
    RecommendTopWalletV2View recommendTopWallet;
    @Bind(R.id.recommendTopDownload)
    RecommendTopDownloadV2View recommendTopDownload;
    @Bind(R.id.bar_title_tx)
    TextView barTitleTx;
    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.backSdv)
    SimpleDraweeView backSdv;
    @Bind(R.id.activityDetailTabs)
    SlidingTabLayout activityDetailTabs;
    @Bind(R.id.activityDetail2Tabs)
    SlidingTabLayout activityDetail2Tabs;
    @Bind(R.id.gameLibTopIv)
    SimpleDraweeView gameLibTopIv;
    @Bind(R.id.gameLibTopAdIv)
    SimpleDraweeView gameLibTopAdIv;
    @Bind(R.id.gameLibGv)
    MyGridView gameLibGv;
    @Bind(R.id.frameLayout)
    FrameLayout frameLayout;
    @Bind(R.id.retryImg)
    ImageView retryImg;
    @Bind(R.id.retryText)
    TextView retryText;
    @Bind(R.id.notNetFl)
    FrameLayout notNetFl;
    @Bind(R.id.viewPager)
    MyViewPager viewPager;
    @Bind(R.id.contentRl)
    RelativeLayout contentRl;
    @Bind(R.id.contentLl)
    LinearLayout contentLl;
    @Bind(R.id.shimmerLayout)
    ShimmerLayout shimmerLayout;
    @Bind(R.id.vp_recommend)
    ConvenientBanner vpRecommend;

    private ControllerListener controllerListener;
    private Animatable mAnimatable;
    private String[] tabs = {"编辑精选", "玩法分类", "网游榜", "单机榜"};
    private List<FragmentPagerAdapter.Item> items;
    private FragmentPagerAdapter mFragmentPagerAdapter;

    private SparseArray<DiscoveryType> discoveryTypes;
    private GameLibraryTopAdapter mAdapter;

    private int heightTop = 0;
    private int disHeightTop = 0;
    private Map<Integer, Integer> map = new HashMap<>();

    private RetrofitManager retrofitManager;
    private Retrofit retrofit;
    private ApiUtil api;
    private Retrofit retrofitLogin;
    private ApiUtil apiLogin;

    private List<JumpBaseBean> topBanner = null;
    private JumpBaseBean adBanner = null;

    private int bannerPO = 0;

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    if (mAnimatable != null) {
                        mAnimatable.stop();
                        mAnimatable.start();
                        handler.removeMessages(1);
                        Message mess = new Message();
                        mess.what = 1;
                        handler.sendMessageDelayed(mess, 2500);
                    }
                    break;
            }
        }
    };

    @SuppressLint("ClickableViewAccessibility")
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_game_library, container, false);
        ButterKnife.bind(this, view);
        EventBus.getDefault().register(this);

        contentLl.setVisibility(View.GONE);
//        frameLayout.setVisibility(View.GONE);
//        activityDetailTabs.setVisibility(View.GONE);

        barTitleTx.setText(getResources().getString(R.string.title_home));
        back.setImageResource(R.mipmap.ic_main_top_search);
        disHeightTop = (int) getActivity().getResources().getDimension(R.dimen.wdp90);

        retrofitManager = RetrofitManager.getInstance(getActivity());
        retrofit = retrofitManager.getRetrofit();
        api = retrofit.create(ApiUtil.class);
        retrofitLogin = retrofitManager.getLoginRetrofit();
        apiLogin = retrofitLogin.create(ApiUtil.class);

        initDiscoveryTypes();
        initData();

        return view;
    }

    private NetResultCacheTable table = null;

    private void initData() {
        try {
            showSkeleton();
            Map<String, String> tempMap = new HashMap<>();
            tempMap.put("pn", "1");
            String requestStr = new Gson().toJson(tempMap);
            table = NetResultCacheManager.getInstance().getDataByUrl(RpcConstant.forumRootUrl + RpcConstant.gameLibraryV3, requestStr);
            if (table != null && !StringUtils.isEmpty(table.getResponseStr())) {
//                hideSkeleton();
                String data = table.getResponseStr();
                ResponseBase<GameLibraryV3Response> temp = fromJsonObject(data, GameLibraryV3Response.class);
                initTabsView(temp.getData_info());
                hideSkeleton();
//                new Handler().postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        getIndexData();
//                    }
//                }, 500);
            } else {
//                getIndexData();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        getIndexData();
    }

    public <T> ResponseBase<T> fromJsonObject(String reader, Class<T> clazz) {
        Type type = new NetCallBack.ParameterizedTypeImpl(ResponseBase.class, new Class[]{clazz});
        return new Gson().fromJson(reader, type);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    getUserinfo();
                }
            }, 500);
        }
    }

    private void getIndexData() {
        if (NetWorkUtils.isNetworkConnected(getActivity())) {
            int uId = 0;
            AccountBean accountBean = AccountUtil.getInstance().getAccountData();
            if (accountBean != null) {
                uId = AccountUtil.getInstance().getUid();
            }
            api.getGameLibraryV3(uId, 1, 0).enqueue(new MyCallback<ResponseBase<GameLibraryV3Response>>() {
                @Override
                public void onSuccess(ResponseBase<GameLibraryV3Response> model) {
                    Gson gson = new Gson();
                    Map<String, String> tempMap = new HashMap<>();
                    tempMap.put("pn", "1");
                    String requestStr = gson.toJson(tempMap);
                    String retStr = gson.toJson(model);
                    String retUrl = RpcConstant.forumRootUrl + RpcConstant.gameLibraryV3;
                    NetResultCacheManager.getInstance().insertData(retUrl, requestStr, retStr);

                    GameLibraryV3Response data = model.getData_info();
                    if (data == null) {
                        notNetFl.setVisibility(View.VISIBLE);
                        contentRl.setVisibility(View.GONE);
                        retryImg.setImageResource(R.mipmap.ic_not_data);
                        retryText.setText("数据获取失败，点击屏幕重新加载");
                    } else {
                        initTabsView(data);
                    }
                    hideSkeleton();
                }

                @Override
                public void onFailure(int code, String msg) {
                    showToast(msg);
                    hideSkeleton();
                    notNetFl.setVisibility(View.VISIBLE);
                    contentRl.setVisibility(View.GONE);
                    retryImg.setImageResource(R.mipmap.ic_not_net);
                    retryText.setText("网络异常，点击屏幕重新加载");
                }
            });
        } else {
            notNetFl.setVisibility(View.VISIBLE);
            contentRl.setVisibility(View.GONE);
            retryImg.setImageResource(R.mipmap.ic_not_net);
            retryText.setText("网络异常，点击屏幕重新加载");
        }
    }

    private void initDiscoveryTypes() {
        if (discoveryTypes == null) {
            discoveryTypes = MyApplication.getMyApplication().getDiscoveryTypes();
        }

        mAdapter = new GameLibraryTopAdapter(getActivity(), discoveryTypes);
        gameLibGv.setAdapter(mAdapter);
    }

    private void initTabsView(GameLibraryV3Response data) {
        topBanner = data.getTop_banner_info();
        if (topBanner != null && topBanner.size() > 0) {
//            gameLibTopIv.setVisibility(View.VISIBLE);
//            gameLibTopIv.setImageURI(topBanner.get(0).getJump_cover_big_pic());
            UtilsMy.setRecommendGoods(getActivity(), vpRecommend, topBanner, false);
            heightTop = (int) getActivity().getResources().getDimension(R.dimen.wdp839);
        } else {
            gameLibTopIv.setVisibility(View.GONE);
            heightTop = (int) getActivity().getResources().getDimension(R.dimen.wdp492);
        }

        adBanner = data.getBanner_ad();
        if (adBanner!=null) {
            gameLibTopAdIv.setVisibility(View.VISIBLE);
            gameLibTopAdIv.setImageURI(adBanner.getJump_cover_big_pic());
            heightTop += (int) getActivity().getResources().getDimension(R.dimen.wdp220);
        } else {
            gameLibTopAdIv.setVisibility(View.GONE);
        }

        items = new ArrayList<>();
        for (int i = 0; i < tabs.length; i++) {
            switch (i) {
                case 0:
                    if (data.getRecommend_info() != null) {
                        Fragment fragment0 = GameLibraryOneFragment.newInstance(this, mAdapter, viewPager, topBanner, data.getRecommend_info(), adBanner);
                        items.add(new FragmentPagerAdapter.Item(tabs[i], fragment0));
                    }
                    break;
                case 1:
                    if (data.getPlay_type_info() != null) {
                        Fragment fragment1 = GameLibraryTwoFragment.newInstance(this, mAdapter, viewPager, topBanner, data.getPlay_type_info(), adBanner);
                        items.add(new FragmentPagerAdapter.Item(tabs[i], fragment1));
                    }
                    break;
                case 2:
                    if (data.getNet_game_ranking_info() != null) {
                        Fragment fragment2 = GameLibraryThreeFragment.newInstance(this, mAdapter, viewPager, topBanner, data.getNet_game_ranking_info(), adBanner, 3);
                        items.add(new FragmentPagerAdapter.Item(tabs[i], fragment2));
                    }
                    break;
                case 3:
                    if (data.getSingle_game_ranking_info() != null) {
                        Fragment fragment3 = GameLibraryFourFragment.newInstance(this, mAdapter, viewPager, topBanner, data.getSingle_game_ranking_info(), adBanner, 4);
                        items.add(new FragmentPagerAdapter.Item(tabs[i], fragment3));
                    }
                    break;
            }
        }

        mFragmentPagerAdapter = new FragmentPagerAdapter(getActivity().getSupportFragmentManager(), items);
        viewPager.setAdapter(mFragmentPagerAdapter);
        viewPager.setCurrentItem(0);
        viewPager.setOffscreenPageLimit(3);
        activityDetailTabs.setViewPager(viewPager);
        activityDetail2Tabs.setViewPager(viewPager);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {
                int num = viewPager.getCurrentItem();
                activityDetail2Tabs.setVisibility(View.GONE);
//                viewPager.setScanScroll(false);
                if (topMap.containsKey(num)) {
                    OnScroll(num, topMap.get(num), 0);
                }
                if (state == ViewPager.SCROLL_STATE_IDLE) {
                    contentLl.setVisibility(View.GONE);
//                    frameLayout.setVisibility(View.GONE);
//                    activityDetailTabs.setVisibility(View.GONE);
                } else {
                    contentLl.setVisibility(View.VISIBLE);
//                    frameLayout.setVisibility(View.VISIBLE);
//                    activityDetailTabs.setVisibility(View.VISIBLE);
                    activityDetailTabs.setCurrentTab(viewPager.getCurrentItem());
                    vpRecommend.setCurrentItem(MyApplication.bannerPo, false);
                    if (topMap.containsKey(num) && topMap.get(num) > (heightTop - disHeightTop)) {
                        contentLl.setVisibility(View.GONE);
//                        frameLayout.setVisibility(View.GONE);
//                        activityDetailTabs.setVisibility(View.GONE);
                    }
                }
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        getUserinfo();

        changeTopStatus();

        boolean isClick = PreferenceUtil.getBoolPreferences(getActivity(), PreferenceUtil.PRE_SEARCH_IS_CILICK);
        if (isClick) {
            back.setVisibility(View.VISIBLE);
            backSdv.setVisibility(View.GONE);
            handler.removeMessages(1);
        } else {
            if (controllerListener == null) {
                controllerListener = new BaseControllerListener<ImageInfo>() {
                    @Override
                    public void onFinalImageSet(
                            String id,
                            @Nullable ImageInfo imageInfo,
                            @Nullable Animatable anim) {
                        mAnimatable = anim;
                        handler.removeMessages(1);
                        Message message = new Message();
                        message.what = 1;
                        handler.sendMessage(message);
                    }
                };
            }

            back.setVisibility(View.GONE);
            backSdv.setVisibility(View.VISIBLE);
            Uri uri = Uri.parse("asset:///aaa.gif");
            DraweeController draweeController = Fresco.newDraweeControllerBuilder().setUri(uri)
                    .setControllerListener(controllerListener)
                    .build();
            backSdv.setController(draweeController);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @OnClick({R.id.back, R.id.backSdv, R.id.notNetFl, R.id.gameLibTopIv, R.id.gameLibTopAdIv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.gameLibTopIv:
                if (topBanner != null && topBanner.size() > 0) {
                    IntentUtil.getInstance().intentTo(getActivity(), topBanner.get(0));
                }
                break;
            case R.id.gameLibTopAdIv:
                if (adBanner != null) {
                    IntentUtil.getInstance().intentTo(getActivity(), adBanner);
                }
                break;
            case R.id.notNetFl:
                getIndexData();
                break;
            case R.id.backSdv:
                PreferenceUtil.saveBoolPreference(getActivity(), PreferenceUtil.PRE_SEARCH_IS_CILICK, true);
            case R.id.back:
                startActivity(new Intent(getActivity(), SearchActivity.class));
                getActivity().overridePendingTransition(R.anim.slide_left_in, R.anim.slide_right_out);
                break;
        }
    }

    private void changeTopStatus() {
        try {
            if (recommendTopDownload != null) {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (recommendTopDownload != null) {
                            recommendTopDownload.setTotalDownloadNum();
                        }
                    }
                }, 200);
            }
        } catch (Exception e) {
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(EnergyEvent energyEvent) {
        if (recommendTopWallet != null) {
            recommendTopWallet.initTotalWalletNum();
        }
    }

    private void getUserinfo() {
        if (NetWorkUtils.isNetworkConnected(getActivity())) {
            try {
                if (AccountUtil.getInstance().getUid() != 0) {
                    int uid = AccountUtil.getInstance().getUid();
                    String token = AccountUtil.getInstance().getToken();
                    apiLogin.checkToken(uid, token).enqueue(new MyCallback<ResponseBase<PersonHomeDataUrl>>() {
                        @Override
                        public void onSuccess(ResponseBase<PersonHomeDataUrl> model) {
                            PersonHomeDataUrl data = model.getData_info();
                            if (data != null) {
                                data.setToken(AccountUtil.getInstance().getToken());
                                AccountUtil.getInstance().saveAccountData(data);
                            }
                        }

                        @Override
                        public void onFailure(int code, String msg) {
                            if (code == 60001) {
                                AccountUtil.getInstance().accountLoginOut(getActivity());
                            }
                            ToastUtils.getInstance(getActivity()).showToastSystem(msg);
                        }
                    });
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private RelativeLayout.LayoutParams params = null;
    private Map<Integer, Integer> topMap = new LinkedHashMap<>();

    @Override
    public void OnScroll(int position, int totalDy, int dy) {
        if (position != viewPager.getCurrentItem())
            return;
        topMap.put(position, totalDy);
        if (totalDy > (heightTop - disHeightTop)) {
            activityDetail2Tabs.setVisibility(View.VISIBLE);
            viewPager.setScanScroll(true);
            contentLl.setVisibility(View.GONE);
//            vpRecommend.setVisibility(View.GONE);
//            frameLayout.setVisibility(View.GONE);
            activityDetailTabs.setVisibility(View.GONE);
        } else {
            activityDetail2Tabs.setVisibility(View.GONE);
            viewPager.setScanScroll(false);
            vpRecommend.setVisibility(View.VISIBLE);
            if (contentLl.getVisibility() == View.VISIBLE) {
//            if (vpRecommend.getVisibility() == View.VISIBLE) {
                if (params == null) {
                    params = (RelativeLayout.LayoutParams) contentLl.getLayoutParams();
                }
                params.topMargin = 0 - totalDy;
                contentLl.setLayoutParams(params);
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEventMainThread(DownloadEvent downloadEvent) {
        recommendTopDownload.setTotalDownloadNum();//设置下载数
    }

//    @Override
//    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
//        Fragment fragment = items.get(viewPager.getCurrentItem()).fragment;
//        if (fragment instanceof GameLibraryOneFragment)
//            ((GameLibraryOneFragment) fragment).onRefresh(refreshLayout);
//        else if (fragment instanceof GameLibraryTwoFragment)
//            ((GameLibraryTwoFragment) fragment).onRefresh(refreshLayout);
//        else if (fragment instanceof GameLibraryThreeFragment)
//            ((GameLibraryThreeFragment) fragment).onRefresh(refreshLayout);
//        else if (fragment instanceof GameLibraryFourFragment)
//            ((GameLibraryFourFragment) fragment).onRefresh(refreshLayout);
//    }

    private void showSkeleton() {
        shimmerLayout.setVisibility(View.VISIBLE);
        contentRl.setVisibility(View.GONE);
        notNetFl.setVisibility(View.GONE);
        if (innerView == null) initSkeleton();
        if (innerView == null) return;
        shimmerLayout.startShimmerAnimation();
    }

    private void hideSkeleton() {
        notNetFl.setVisibility(View.GONE);
        shimmerLayout.setVisibility(View.GONE);
        contentRl.setVisibility(View.VISIBLE);
        if (innerView == null) initSkeleton();
        if (innerView == null) return;
        shimmerLayout.stopShimmerAnimation();
    }

    private int mShimmerColor;
    private boolean mShimmer = true;
    private int mShimmerDuration = 1200;
    private int mShimmerAngle = 20;
    View innerView;

    private void initSkeleton() {
        mShimmerColor = ContextCompat.getColor(getActivity(), R.color.shimmer_color);

        shimmerLayout.setShimmerColor(mShimmerColor);
        shimmerLayout.setShimmerAngle(mShimmerAngle);
        shimmerLayout.setShimmerAnimationDuration(mShimmerDuration);

        innerView = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_game_lib_skeleton, shimmerLayout, false);
        shimmerLayout.addView(innerView);
        shimmerLayout.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() {
            @Override
            public void onViewAttachedToWindow(View v) {
                shimmerLayout.startShimmerAnimation();
            }

            @Override
            public void onViewDetachedFromWindow(View v) {
                shimmerLayout.stopShimmerAnimation();
            }
        });
    }
}
